package com.yupi.yupicturebackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {


    @Resource
    private CosManager cosManager;

    //文件测试上传
    @PostMapping("/test/upload")
    @AuthCheck(mustRole = "admin")
    public BaseResponse< String>testUploadFile(@RequestPart MultipartFile  multipartFile){

        //文件目录
        String fileName=multipartFile.getOriginalFilename();
        String filePath=String.format("/test/%s",fileName);

        File  file=null;

        try {
          file = File.createTempFile(filePath, null);
          multipartFile.transferTo(file);
          cosManager.putObject(filePath,file);
          //返回可访问的地址
            return ResultUtils.success(filePath);
        } catch (IOException e) {
            log.error("file upload error{}",filePath,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }finally {
            if(file != null){
                //删除临时文件
                boolean delete = file.delete();
                if(!delete){
                    log.error("file delete error{}",filePath);
                }
            }
        }

    }

    //文件测试下载
    @GetMapping("/test/download")
    @AuthCheck(mustRole = "admin")
    public void testDownloadFile(@RequestParam String filePath, HttpServletResponse response) throws IOException {

        COSObjectInputStream cosObjectInputStream = null;
        try {
            cosObjectInputStream = null;
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInputStream = cosObject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInputStream);

            //设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
        } catch (IOException e) {
            log.error("file download error{}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            //释放流

            if(cosObjectInputStream != null){
                cosObjectInputStream.close();
            }
        }

    }





}
